package cn.qiyu5522.tk_ems.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.*;
import cn.qiyu5522.tk_ems.entity.dto.CompanyEmployRecordDTO;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.entity.vo.CompanyEmployRecordVO;
import cn.qiyu5522.tk_ems.entity.vo.JobVO;
import cn.qiyu5522.tk_ems.mapper.*;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.CompanyEmployRecordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 公司录用记录表 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-03-05
 */
@Service
public class CompanyEmployRecordServiceImpl extends ServiceImpl<CompanyEmployRecordMapper, CompanyEmployRecord> implements CompanyEmployRecordService {

    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private JobMapper jobMapper;
    @Resource
    private JobcategoryMapper jobcategoryMapper;

    @Override
    public R queryCompanyEmployRecordByPageCondition(QueryParamDTO<CompanyEmployRecordDTO> queryParamDTO) {
        CompanyEmployRecordDTO condition = queryParamDTO.getCondition();
        IPage<CompanyEmployRecord> companyEmployRecordIPage = new Page<>(queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize());
        LambdaQueryWrapper<CompanyEmployRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据创建时间<===>企业点击确认面试按钮时添加记录的时间
        lambdaQueryWrapper.ge(ObjectUtil.isNotEmpty(condition.getCreateTime()), CompanyEmployRecord::getCreateTime, condition.getCreateTimeStart())
                .le(ObjectUtil.isNotEmpty(condition.getCreateTime()), CompanyEmployRecord::getCreateTime, condition.getCreateTimeEnd())
                // 录用时间
                .ge(ObjectUtil.isNotEmpty(condition.getEmployTime()), CompanyEmployRecord::getEmployTime, condition.getEmployTimeStart())
                .le(ObjectUtil.isNotEmpty(condition.getEmployTime()), CompanyEmployRecord::getEmployTime, condition.getEmployTimeEnd());
        // 获取用户编号
        Object loginId = StpUtil.getLoginId();
        Long userId = Long.valueOf(((String) loginId).split("-")[0]);
        List<String> roleList = StpUtil.getRoleList();
        boolean adminRole = roleList.stream().anyMatch(s -> "admin".equals(s));
        boolean companyRole = roleList.stream().anyMatch(s -> "company".equals(s));
        // 如果是管理员则全查
        if (adminRole) {
            baseMapper.selectPage(companyEmployRecordIPage, lambdaQueryWrapper);
        } else if (companyRole) {
            // 根据公司编号，查询对应公司的简历投递状态
            lambdaQueryWrapper.eq(CompanyEmployRecord::getCompanyId, userId);
            baseMapper.selectPage(companyEmployRecordIPage, lambdaQueryWrapper);
        }
        // 实体转VO
        List<CompanyEmployRecordVO> companyEmployRecordVOS = objectMapper
                .convertValue(companyEmployRecordIPage.getRecords(),
                        new TypeReference<List<CompanyEmployRecordVO>>() {
                        });
        if (companyEmployRecordVOS.size() == 0) {
            Map<String, Object> map = CustomMapResult.packagingResult(
                    new ArrayList(0),
                    queryParamDTO.getCurrentPage(),
                    queryParamDTO.getPageSize(),
                    companyEmployRecordIPage.getTotal());
            return R.ok().data("companyEmployRecordIPage", map);
        }
        // 映射学生姓名
        List<Long> studentIds = companyEmployRecordVOS.stream().map(CompanyEmployRecordVO::getStudentId).collect(Collectors.toList());
        List<Student> students = studentMapper.selectBatchIds(studentIds);
        for (Student student : students) {
            companyEmployRecordVOS.forEach(companyEmployRecordVO -> {
                if (companyEmployRecordVO.getStudentId().equals(student.getId())) {
                    companyEmployRecordVO.setStudentName(student.getName());
                }
            });
        }
        // 映射公司名称
        List<Long> companyIds = companyEmployRecordVOS.stream().map(CompanyEmployRecordVO::getCompanyId).collect(Collectors.toList());
        List<Company> companies = companyMapper.selectBatchIds(companyIds);
        for (Company company : companies) {
            companyEmployRecordVOS.forEach(companyEmployRecordVO -> {
                if (companyEmployRecordVO.getCompanyId().equals(company.getId())) {
                    companyEmployRecordVO.setCompanyName(company.getName());
                }
            });
        }
        // 映射岗位名称
        // 根据岗位编号查询岗位名称
        List<Integer> jobIds = companyEmployRecordVOS.stream().map(CompanyEmployRecordVO::getJobId).collect(Collectors.toList());
        List<Job> jobs = jobMapper.selectBatchIds(jobIds);
        // 根据岗位名称里放的值职位的编号,还需要去查询职位分类表中对应的id
        List<Integer> jobNameIds = jobs.stream().map(job -> Integer.valueOf(job.getName())).collect(Collectors.toList());
        List<JobCategory> jobCategories = jobcategoryMapper.selectBatchIds(jobNameIds);
        // job实体转jobVO
        List<JobVO> jobVOS = objectMapper.convertValue(jobs, new TypeReference<List<JobVO>>() {
        });
        for (JobCategory jobCategory : jobCategories) {
            jobVOS.forEach(jobVO -> {
                if (jobCategory.getId().equals(Integer.valueOf(jobVO.getName()))) {
                    jobVO.setJobName(jobCategory.getName());
                }
            });
        }
        for (JobVO jobVO : jobVOS) {
            companyEmployRecordVOS.forEach(companyEmployRecordVO -> {
                if (companyEmployRecordVO.getJobId().equals(jobVO.getId())) {
                    companyEmployRecordVO.setJobName(jobVO.getJobName());
                }
            });
        }
        Map<String, Object> map = CustomMapResult.packagingResult(
                companyEmployRecordVOS,
                queryParamDTO.getCurrentPage(),
                queryParamDTO.getPageSize(),
                companyEmployRecordIPage.getTotal());
        return R.ok().data("companyEmployRecordIPage", map);
    }

    @Override
    public R saveMore(List<CompanyEmployRecordDTO> companyEmployRecordDTOS) {
        // DTO 转实体
        List<CompanyEmployRecord> companyEmployRecords = objectMapper.convertValue(companyEmployRecordDTOS, new TypeReference<List<CompanyEmployRecord>>() {
        });
        LambdaQueryWrapper<CompanyEmployRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        for (CompanyEmployRecord companyEmployRecord : companyEmployRecords) {
            lambdaQueryWrapper.eq(CompanyEmployRecord::getJobId,companyEmployRecord.getJobId())
                    .eq(CompanyEmployRecord::getStudentId, companyEmployRecord.getStudentId())
                    .eq(CompanyEmployRecord::getCompanyId, companyEmployRecord.getCompanyId())
                    .eq(CompanyEmployRecord::getResumeId, companyEmployRecord.getResumeId());
            CompanyEmployRecord companyEmployRecord1 = baseMapper.selectOne(lambdaQueryWrapper);
            if(ObjectUtil.isNotEmpty(companyEmployRecord1)){
                return R.error().message("该学生已处理待面试状态,请勿重复添加");
            }
        }
        Integer integer = baseMapper.insertBatchSomeColumn(companyEmployRecords);
        return integer>0?R.ok().message("添加成功"):R.error().message("添加失败");
    }
}
